package com.leyou.page.service;

import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    @Value("${ly.static.itemDir}")
    private String itemDir;

    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    @Autowired
    private SpringTemplateEngine templateEngine;

    public Map<String, Object> loadItemPage(Long spuId) {
        //根据spuId查询SpuDTO对象
        SpuDTO spuDTO = itemClient.findSpuDTOBySpuId(spuId);
        //根据分类id集合查询分类对象集合
        List<Category> categories = itemClient.findCategoryByIds(spuDTO.getCategoryIds());
        //根据品牌id查询品牌对象
        Brand brand = itemClient.getBrandById(spuDTO.getBrandId());
        //根据第三级分类id查询规格组集合
        List<SpecGroupDTO> specGroupDTOS = itemClient.findSpecGroupDTOByCid(spuDTO.getCid3());

        Map<String, Object> itemData = new HashMap<>();
        itemData.put("categories", categories);
        itemData.put("brand", brand);
        itemData.put("spuName", spuDTO.getName());
        itemData.put("subTitle", spuDTO.getSubTitle());
        itemData.put("detail", spuDTO.getSpuDetail());
        itemData.put("skus", spuDTO.getSkus());
        itemData.put("specs", specGroupDTOS);
        return itemData;
    }

    /**
     * 创建静态化页面并把静态化页面写入静态资源服务器中
     */
    public void createStaticPage(Long spuId){
        //获取上下文
        Context context = new Context();
        context.setVariables(loadItemPage(spuId));

        //指定当前静态页面的名称
        String pageName = spuId+".html";
        //指定静态页所在服务器文件对象
        File staticPageFile = new File(new File(itemDir), pageName);

        //创建打印流
        try(PrintWriter write = new PrintWriter(staticPageFile)){
            templateEngine.process(itemTemplate, context, write);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }

    }

    public void deleteStaticPage(Long id) {
        //指定当前静态页面的名称
        String pageName = id+".html";
        //指定静态页所在服务器文件对象
        File staticPageFile = new File(new File(itemDir), pageName);
        //判断如果页面存在，就删除
        if(staticPageFile.exists()){
            staticPageFile.delete();
        }
    }
}
